//
//  RestaurantTableViewController.m
//  Gourmet
//
//  Created by WardenAllen on 15/11/15.
//  Copyright © 2015年 王东. All rights reserved.
//

#import "RestaurantTableViewController.h"
#import "DropDownChooseProtocol.h"
#import "DropDownListView.h"
#import "MJRefresh.h"
#import "AppDelegate.h"
#import "RestaurantDetailTableViewController.h"
#import "RestaurantTableViewCell.h"

@interface RestaurantTableViewController () <DropDownChooseDataSource, DropDownChooseDelegate> {
    NSMutableArray *dropDownListArray;
}

@property (strong) NSMutableArray *logoDataSource;
@property (strong) NSMutableArray *otherDataSource;
@property (nonatomic, assign) NSInteger skipNumber;

@end

@implementation RestaurantTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.skipNumber = 0;
    
    self.logoDataSource = [NSMutableArray array];
    self.otherDataSource = [NSMutableArray array];
    
    dropDownListArray = [NSMutableArray arrayWithArray:@[
                                                   @[@"全部分类", @"东北菜", @"川菜"],
                                                   @[@"智能排序", @"离我最近", @"价格最低"]
                                                   ]];

    self.tableView.tableFooterView = [[UIView alloc] init];
    
    __unsafe_unretained UITableView *tableView = self.tableView;

    // 下拉刷新
    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.logoDataSource = [NSMutableArray array];
        self.otherDataSource = [NSMutableArray array];
        AVQuery *query = [AVQuery queryWithClassName:@"RestaurantInfo"];
        self.skipNumber = 0;
        query.skip = self.skipNumber;
        query.limit = 20;
        //[query whereKey:@"restaurantId" equalTo:@1];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                // 检索成功
                NSLog(@"Successfully retrieved %lu posts.", (unsigned long)objects.count);
                for (int i=0; i<objects.count; i++) {
                    AVObject *restaurantInfo = objects[i];
                    AVFile *file = [restaurantInfo objectForKey:@"restaurantLogo"];
                    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                        if (!error) {
                            [self.logoDataSource addObject:[UIImage imageWithData:data]];
                            [restaurantInfo removeObjectForKey:@"restaurantLogo"];
                            [self.otherDataSource addObject:restaurantInfo];
                            if (self.logoDataSource.count == objects.count) {
                                [self.tableView reloadData];
                                NSLog(@"%@", self.otherDataSource);
                                [tableView.mj_header endRefreshing];
                            }
                        } else {
                            NSLog(@"%@ %@", error, [error userInfo]);
                            [tableView.mj_header endRefreshing];
                        }
                    }];
                }
            } else {
                // 输出错误信息
                NSLog(@"Error: %@ %@", error, [error userInfo]);
                [tableView.mj_header endRefreshing];
            }
        }];

        
    }];

    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;

    // 上拉刷新
    tableView.mj_offsetY = -22.;
    tableView.mj_footer.frame = CGRectMake(60, kHEIGHT-50, 200, 50);
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (self.otherDataSource.count%20 == 0) {
            self.skipNumber += 20;
            
            AVQuery *query = [AVQuery queryWithClassName:@"RestaurantInfo"];
            query.skip = self.skipNumber;
            query.limit = 20;
            //[query whereKey:@"restaurantId" equalTo:@1];
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                if (!error) {
                    // 检索成功
                    NSLog(@"Successfully retrieved %lu posts.", (unsigned long)objects.count);
                    for (int i=0; i<objects.count; i++) {
                        AVObject *restaurantInfo = objects[i];
                        AVFile *file = [restaurantInfo objectForKey:@"restaurantLogo"];
                        [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                            if (!error) {
                                [self.logoDataSource addObject:[UIImage imageWithData:data]];
                                [restaurantInfo removeObjectForKey:@"restaurantLogo"];
                                [self.otherDataSource addObject:restaurantInfo];
                                if (self.logoDataSource.count == (objects.count+self.skipNumber)) {
                                    [self.tableView reloadData];
                                    NSLog(@"%@", self.otherDataSource);
                                    [tableView.mj_footer endRefreshing];
                                }
                            } else {
                                NSLog(@"%@ %@", error, [error userInfo]);
                                [tableView.mj_footer endRefreshing];
                            }
                        }];
                    }
                } else {
                    // 输出错误信息
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    [tableView.mj_footer endRefreshing];
                }
            }];
            
        } else {
            [tableView.mj_footer endRefreshing];
        }
    }];
    
    [tableView.mj_header beginRefreshing];
    AVQuery *query = [AVQuery queryWithClassName:@"RestaurantInfo"];
    query.skip = self.skipNumber;
    query.limit = 20;
    //[query whereKey:@"restaurantId" equalTo:@1];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            NSLog(@"Successfully retrieved %lu posts.", (unsigned long)objects.count);
            for (int i=0; i<objects.count; i++) {
                AVObject *restaurantInfo = objects[i];
                AVFile *file = [restaurantInfo objectForKey:@"restaurantLogo"];
                [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                    if (!error) {
                        [self.logoDataSource addObject:[UIImage imageWithData:data]];
                        [restaurantInfo removeObjectForKey:@"restaurantLogo"];
                        [self.otherDataSource addObject:restaurantInfo];
                        if (self.logoDataSource.count == objects.count) {
                            [self.tableView reloadData];
                            NSLog(@"%@", self.otherDataSource);
                            [tableView.mj_header endRefreshing];
                        }
                    } else {
                        NSLog(@"%@ %@", error, [error userInfo]);
                        [tableView.mj_header endRefreshing];
                    }
                }];
            }
        } else {
            // 输出错误信息
            NSLog(@"Error: %@ %@", error, [error userInfo]);
            [tableView.mj_header endRefreshing];
        }
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    DropDownListView *listView = [[DropDownListView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 44*kWIDTH_RATIO) dataSource:self delegate:self];
    listView.mSuperView = self.view;
    return listView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44*kWIDTH_RATIO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100*kWIDTH_RATIO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.logoDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RestaurantTableViewCell *restaurantCell = [tableView dequeueReusableCellWithIdentifier:@"RestaurantCell" forIndexPath:indexPath];
    AVObject *otherInfo = self.otherDataSource[indexPath.row];
    restaurantCell.nameLabel.text = [otherInfo objectForKey:@"restaurantName"];
    restaurantCell.logoImageView.image = self.logoDataSource[indexPath.row];
    
    return restaurantCell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RestaurantDetailTableViewController *rdtvc = (RestaurantDetailTableViewController *)[[AppDelegate globalDelegate] RestaurantDetailTableViewController];
    AVObject *otherInfo = [self.otherDataSource objectAtIndex:indexPath.row];
    //先转化为NSString
    NSString *restaurantId = [otherInfo objectForKey:@"restaurantId"];
    NSString *restaurantName = [otherInfo objectForKey:@"restaurantName"];
    float rank = [[otherInfo objectForKey:@"rank"] floatValue];
    NSString *rankCount = [otherInfo objectForKey:@"rankCount"];

    rdtvc.restaurantId = [restaurantId integerValue];
    rdtvc.restaurantName = restaurantName;
    rdtvc.rank = rank;
    rdtvc.rankCount = [rankCount integerValue];
    
    [self.navigationController pushViewController:rdtvc animated:YES];
}


#pragma mark -- dropDownListDelegate
-(void) chooseAtSection:(NSInteger)section index:(NSInteger)index
{
    NSLog(@"WardenAllen选了section:%ld ,index:%ld",(long)section,(long)index);
}

#pragma mark -- dropdownList DataSource
-(NSInteger)numberOfSections
{
    return [dropDownListArray count];
}
-(NSInteger)numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = dropDownListArray[section];
    return [array count];
}
-(NSString *)titleInSection:(NSInteger)section index:(NSInteger) index
{
    return dropDownListArray[section][index];
}
-(NSInteger)defaultShowSection:(NSInteger)section
{
    return 0;
}

@end
